<template>
  <div class="dataContainer">
    <!-- Search start -->
    <el-form :inline="true" size="small" :model="queryParams" class="demo-form-inline searchContainer">
      <el-form-item label="姓名: ">
        <el-input v-model="queryParams.userName" placeholder="请输入姓名"  @keyup.enter="onSearch" />
      </el-form-item>
      <el-form-item label="账号: ">
        <el-input v-model="queryParams.userAccount"  placeholder="请输入账号"  @keyup.enter="onSearch" />
      </el-form-item>
      <el-form-item label="用户状态:">
        <el-select v-model="queryParams.userStatus" placeholder="请选择" collapse-tags clearable  style="width: 150px">
          <el-option label="启用" :value="1" />
          <el-option label="冻结" :value="2" />
          <el-option label="删除" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button class="bs-form-btn" size="small" type="primary" @click="onSearch" ><el-icon><Search /></el-icon>查 询</el-button>
        <ResetButton :queryParams="queryParams"/>
        <el-button size="small" type="primary" @click="openModal" v-permission="['system::userAdd']"><el-icon><Plus /></el-icon>新增 </el-button>
        <!-- <el-button size="small" type="primary" @click="columnSort()" ><el-icon><Plus /></el-icon>列排序 </el-button> -->
      </el-form-item>
    </el-form>
    <!-- Search end -->

    <!-- Table start -->
    <div>
      <ColumnSetting v-model:columnList="columnList" />
      <el-table
        ref="tableRef"
        v-loading="tableLoading"
        :border="true"
        class="bs-table"
        :data="tableData"
        row-key="userId"
        :height="tableHeight"
        :header-cell-style="{textAlign: 'center'}"
        :cell-style="{textAlign: 'center'}"
         table-layout='auto'
      >
        <el-table-column type="index" label="序号" width="80"/>
        <template v-for="item in columnList" :key="item.prop">
          <el-table-column :prop="item.prop" :label="item.label" :sortable:="item.sortable" v-if="!item.hide && item.prop!='action'">
            <template #default="scope">
              <template v-if="item.prop=='userStatus'">
                <div :style="{'background':getBgColor(scope.row.userStatus)}" class="tagClass"> {{ getStatus(scope.row.userStatus) }} </div>
              </template>
              <template v-else-if="item.prop=='roleNameList'">
                <template v-for="roleName in scope.row.roleNameList" :key="roleName">
                  <el-tag type='primary' style="margin-right: 5px;">{{ roleName }}</el-tag>
                </template>
              </template>
              <template v-else-if="item.prop=='action'">
                <el-button  size="small" link type="success"  @click="userEdit(scope.row.userId)" v-permission="['system::userUpdate']"><el-icon><Edit /></el-icon> 修改</el-button>
                <el-button  size="small" link type="warning"  @click="resetPwd(scope.row.userId)" v-permission="['system::userResetPwd']"><el-icon><Refresh /></el-icon> 重置密码</el-button>
                <el-button  size="small" link type="danger" @click="deleteUser(scope.row.userId)" v-permission="['system::userDelete']"><el-icon><Delete /></el-icon> 删除</el-button>
                <!-- <el-table-column fixed="right" label="操作" width="240" v-permission="['system::userUpdate','system::userDelete','system::userResetPwd']">
                  <template #default="scope" >
                  </template>
                </el-table-column> -->
              </template>
              <template v-else>
                {{ scope.row[item.prop] }}
              </template>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="240" v-permission="['system::userUpdate','system::userDelete','system::userResetPwd']" v-else-if="!item.hide && item.prop=='action'">
             <template #default="scope">
              <el-button  size="small" link type="success"  @click="userEdit(scope.row.userId)" v-permission="['system::userUpdate']"><el-icon><Edit /></el-icon> 修改</el-button>
              <el-button  size="small" link type="warning"  @click="resetPwd(scope.row.userId)" v-permission="['system::userResetPwd']"><el-icon><Refresh /></el-icon> 重置密码</el-button>
              <el-button  size="small" link type="danger" @click="deleteUser(scope.row.userId)" v-permission="['system::userDelete']"><el-icon><Delete /></el-icon> 删除</el-button>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <pagination
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        small="small"
        disabled="disabled"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableTotal"
        @pagination="selectByPage"
      />
    </div>
    <AddUser ref="addRef" @flushTable="selectByPage" />
    <EditUser ref="editRef" @flushTable="selectByPage" />
  </div>
</template>

<script>
import { selectByPage, deleteUser, updateUserPwd, exportUser } from '@/api/system/user'
import { ElPagination } from 'element-plus'
import AddUser from './addUser.vue'
import EditUser from './editUser.vue'
import { mapState } from 'vuex'

export default {
  components: {
    ElPagination,
    AddUser,
    EditUser
  },
  data() {
    return {
      tableTotal: 0,
      tableLoading: false,
      tableData: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 500,
        userName: '',
        userAccount: '',
        userStatus: ''
      },
      dateRange: [],
      selectedRows: [], // 勾选一行或多行数据
      columnList:[
        {prop:'userName',label:'姓名',sortable:false,sort:1,hide:false,fixed:false},
        {prop:'userAccount',label:'账号',sortable:false,sort:2,hide:false,fixed:false},
        {prop:'userStatus',label:'状态',sortable:false,sort:3,hide:false,fixed:false},
        {prop:'roleNameList',label:'角色',sortable:false,sort:4,hide:false,fixed:false},
        {prop:'action',label:'操作',sortable:false,sort:5,hide:false,fixed:'right'},
      ],
      tableHeight:(window.innerHeight - 360) + 'px',
    }
  },
  created() {
    // 列按照sort升序
    this.columnList = this.columnList.sort((a,b)=>a.sort-b.sort)
    this.selectByPage()
  },
  computed:{
    ...mapState(['amplify'])
  },
  mounted(){
    this.countTableHeight()
  },
  methods: {
    testExport(){
      exportUser({})
    },
    
    // columnSort(){
    //   this.columnList.splice(0,1)
    //   this.columnList.push({prop:'userName',label:'姓名',sortable:false,sort:5})
    // },
    selectByPage() {
      this.tableLoading = true
      selectByPage(this.queryParams)
        .then((res) => {
          this.tableLoading = false
          if (res.code === 1) {
            this.tableData = res.data.records
            this.tableTotal = res.data.total
          }
        })
        .catch(() => {
          this.tableLoading = false
        })
    },
    // 搜索
    onSearch() {
      this.queryParams.pageNo = 1
      this.selectByPage()
    },
    onClickAdd() {
    },
    // 不同状态返回不同颜色
    getBgColor(status) {
      if (status == 1) {
        return '#1890ff'
      } else if (status == 2) {
        return '#c5c744'
      } if (status == 3) {
        return 'red'
      }
    },
    getStatus(status) {
      if (status == 1) {
        return '启用'
      } else if (status == 2) {
        return '冻结'
      } if (status == 3) {
        return '删除'
      }
    },
    // 打开新增弹框
    openModal() {
      // 调用子组件中的方法打开弹框
      this.$refs.addRef.openModal()
    },
    // 打开修改弹框
    userEdit(userId) {
      this.$refs.editRef.openModal(userId)
    },
    deleteUser(userId) {
      this.$confirm('请确认是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser({ 'userId': userId }).then(res => {
          if (res.code == 1) {
            this.$message.success('操作成功')
            this.selectByPage()
          }
        })
      }).catch(()=>{})
    },
    resetPwd(userId) {
      this.$confirm('请确认是否重置密码? 重置后密码为123456', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        updateUserPwd({ 'userId': userId ,'userPwd':'123456'}).then(res => {
          if (res.code == 1) {
            this.$message.success('操作成功')
            this.selectByPage()
          }
        })
      }).catch(()=>{})
    },
     // 表格高度
		countTableHeight(){
			let tableHeight = (window.innerHeight - 360) + 'px'
			// 计算搜索区域
			var searchContainerList =  document.getElementsByClassName("searchContainer")
			if (this.arrIsNotEmpty(searchContainerList) && this.arrIsNotEmpty(searchContainerList[0])) {
          let searchContainerHeight = searchContainerList[0].offsetHeight
          // header高度+面包屑高度+tab多标签页高度+tab多标签页底部margin的高度
          let staticHeight = 60+38+30+10
          if (this.amplify == true) {
              // 放大后 , 就没有头部, 面包屑, tab多标签页了 , 预留70px给空白 , 并预留50px给分页
              tableHeight = window.innerHeight - searchContainerHeight - 50 - 70 + 'px'
          } else {
              tableHeight = window.innerHeight - (staticHeight + searchContainerHeight) - 50 - 50 + 'px'
          }
          this.tableHeight = tableHeight
      }
      console.log("表格高度=",this.tableHeight);
		},
  },
  watch: {
		amplify(newValue,oldValue) {
			this.countTableHeight()
		},
	},
}
</script>

<style scoped>
.tagClass {
  display: inline-block;
  padding: 0px 10px;
  font-size: 12px;
  color: white;
  border-width: 1px;
  border-style: solid;
  border-radius: 4px;
  word-break: break-word;
}

.b-tag-warning {
  display: inline-block;
  margin: 0.2rem;
  padding: 5px 10px;
  font-size: 12px;
  color: #ffba00;
  background: #fff8e6;
  border: 1px solid #fff1cc;
  border-radius: 4px;
}

.b-tag-error {
  display: inline-block;
  margin: 0.2rem;
  padding: 5px 10px;
  font-size: 12px;
  color: #ff4949;
  background: #ffeded;
  border: 1px solid #ffdbdb;
  border-radius: 4px;
}

.b-tag-success {
  display: inline-block;
  margin: 0.2rem;
  padding: 5px 10px;
  font-size: 12px;
  color: #13ce66;
  background: #e7faf0;
  border: 1px solid #d0f5e0;
  border-radius: 4px;
}
/* table表格内容样式居中(列宽不够时,所有列居左展示) */
/deep/.el-scrollbar__wrap,/deep/ .el-scrollbar__wrap--hidden-default {
  text-align: left;
}
</style>
